package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.insurance.pojo.CategorySafeguard;
import com.itheima.sfbx.insurance.pojo.PlanSafeguard;
import com.itheima.sfbx.insurance.pojo.Safeguard;
import com.itheima.sfbx.insurance.mapper.SafeguardMapper;
import com.itheima.sfbx.insurance.service.ICategorySafeguardService;
import com.itheima.sfbx.insurance.service.IPlanSafeguardService;
import com.itheima.sfbx.insurance.service.ISafeguardService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.itheima.sfbx.insurance.constant.SafeguardCacheConstant;
import com.itheima.sfbx.insurance.dto.SafeguardVO;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.framework.commons.utils.EmptyUtil;
import com.itheima.sfbx.framework.commons.utils.ExceptionsUtil;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.google.common.collect.Lists;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import lombok.extern.slf4j.Slf4j;
/**
 * @Description：保障项服务实现类
 */
@Slf4j
@Service
public class SafeguardServiceImpl extends ServiceImpl<SafeguardMapper, Safeguard> implements ISafeguardService {

    @Autowired
    private IPlanSafeguardService planSafeguardService;
    @Autowired
    private ICategorySafeguardService categorySafeguardService;


    private LambdaQueryWrapper<Safeguard> queryWrapper(SafeguardVO safeguardVO){
        LambdaQueryWrapper<Safeguard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(safeguardVO.getSafeguardKey()),Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .like(StrUtil.isNotBlank(safeguardVO.getSafeguardKeyName()),Safeguard::getSafeguardKeyName, safeguardVO.getSafeguardKeyName())
                .eq(StrUtil.isNotBlank(safeguardVO.getDataState()),Safeguard::getDataState, safeguardVO.getDataState());
        return  queryWrapper;
    }

    @Override
    public Page<SafeguardVO> findPage(SafeguardVO safeguardVO, int pageNum, int pageSize) {
        //TODO
        LambdaQueryWrapper<Safeguard> queryWrapper = queryWrapper(safeguardVO);
        Page<Safeguard> page = this.page(new Page<>(pageNum, pageSize), queryWrapper);
        Page<SafeguardVO> pageVo = BeanConv.toPage(page, SafeguardVO.class);
        return pageVo;
    }

    @Override
    public SafeguardVO findById(String safeguardId) {
        //TODO
        return null;
    }

    @Override
    @Transactional
    public SafeguardVO save(SafeguardVO safeguardVO) {
        //TODO
        Integer count = lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .eq(Safeguard::getDataState,SuperConstant.DATA_STATE_0)
                .count();
        if(count>0){
            //说明key重复，不能新增
            log.error("新增保障想失败，因为key已经存在:{}",safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.SAVE_FAIL);
        }
        Safeguard bean = BeanConv.toBean(safeguardVO, Safeguard.class);
        this.save(bean);
        return BeanConv.toBean(bean,SafeguardVO.class);
    }

    @Override
    @Transactional
    public Boolean update(SafeguardVO safeguardVO) {
        //TODO
        Safeguard bean = this.getById(safeguardVO.getId());
        if(bean==null){
            log.error("数据不存在：{}",safeguardVO.getId());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        Integer count = lambdaQuery()
                .eq(Safeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .ne(Safeguard::getId, safeguardVO.getId())
                .count();
        if(count>0){
            log.error("修改保障项失败，因为key已经存在:{}",safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        Integer count1 = categorySafeguardService.lambdaQuery()
                .eq(CategorySafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        Integer count2 = planSafeguardService.lambdaQuery()
                .eq(PlanSafeguard::getSafeguardKey, safeguardVO.getSafeguardKey())
                .count();
        if(count1>0||count2>0){
            log.error("修改保障项失败，有关联关系：{}",safeguardVO.getSafeguardKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        return updateById(BeanConv.toBean(safeguardVO,Safeguard.class));
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //TODO
        if(checkedIds==null||checkedIds.length==0){
            return true;
        }
        List<Long> ids = new ArrayList<>();
        for (String checkedId : checkedIds) {
            ids.add(Long.parseLong(checkedId));
        }
        List<Safeguard> safeguards = this.listByIds(ids);
        if (CollUtil.isEmpty(safeguards)) {
            return true;
        }
        Set<String> keySet = safeguards.stream().map(Safeguard::getSafeguardKey).collect(Collectors.toSet());
        Integer count1 = categorySafeguardService.lambdaQuery()
                .in(CategorySafeguard::getSafeguardKey, keySet)
                .eq(CategorySafeguard::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        Integer count2 = planSafeguardService.lambdaQuery()
                .in(PlanSafeguard::getSafeguardKey, keySet)
                .eq(PlanSafeguard::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if(count1>0||count2>0){
            log.error("删除保障项失败，因为存在其他关联关系：{}",keySet);
            throw new ProjectException(SafeguardEnum.DEL_FAIL);
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<SafeguardVO> findList(SafeguardVO safeguardVO) {
        //TODO
        return null;
    }


    @Override
    public List<SafeguardVO> findShowPageItemByKey(List<String> safeguardKeyList) {
        //TODO
        return null;
    }

    @Override
    public SafeguardVO findBySafeguardKey(String safeguardKey) {
        //TODO
        return null;
    }
}
